/*	Copyright 2013 RangerUFO
 *
 *	This file is part of Libevent-helper.
 *
 *	Libevent-helper is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU Lesser General Public License as published by
 *	the Free Software Foundation, either version 3 of the License, or
 *	(at your option) any later version.
 *
 *	Libevent-helper is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU Lesser General Public License for more details.
 *
 *	You should have received a copy of the GNU Lesser General Public License
 *	along with Libevent-helper.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <event2/helper.h>
#include <event2/session.h>
#include <stdio.h>
#include <stdlib.h>

void read_cb(struct evsession* s, void* args)
{
	struct evbuffer* in = evsession_get_input(s);

	for (char* line = evbuffer_readln(in, 0, EVBUFFER_EOL_CRLF); line; evhelper_free(line), line = evbuffer_readln(in, 0, EVBUFFER_EOL_CRLF))
	{
		puts(line);
		fflush(stdout);
	}
}

void event_cb(struct evsession* s, short what, void* args)
{
	if (what & (BEV_EVENT_EOF | BEV_EVENT_ERROR))
	{
		puts("Host disconnect.");
		fflush(stdout);
	}
}

int main(int argc, char* argv[])
{
	if (argc != 3)
	{
		puts("usage: echo_client addr port");
		return -1;
	}

	if (evhelper_init() == -1)
	{
		puts("Init evhelper failed.");
		return -1;
	}

	struct event_base* base = event_base_new();

	if (!base)
	{
		puts("Create event_base failed.");
		return -1;
	}

	struct evsession* s = evsession_new(base, -1);

	if (!s)
	{
		puts("Create evsession failed.");
		event_base_free(base);
		return -1;
	}

	evsession_setcb(s, read_cb, 0, event_cb, 0);

	if (evsession_connect_hostname(s, argv[1], atoi(argv[2])) == -1)
	{
		printf("Connect to %s:%d failed.\n", argv[1], atoi(argv[2]));
		evsession_free(s);
		event_base_free(base);
		return -1;
	}

	char line[2048];

	evbuffer_add_printf(evsession_get_output(s), "%s\r\n", gets(line));

	int ret = event_base_dispatch(base);

	evsession_free(s);
	event_base_free(base);

	return ret;
}
